package org.vt.scheduleapp;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class DisplayTodo extends ListActivity{

	private ToDoReader reader;
	private ToDoWriter writer;
	private List<ToDoList> todo;
	private Context Ctx;
	
	public void onCreate(Bundle savedInstanceState){
		Ctx = this;
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.display_todolist);
		registerForContextMenu(getListView());
		
		reader = new ToDoReader(this);
		todo = new ArrayList<ToDoList>();
		
		try{
			todo = reader.getAllTodo();
		} catch(FileNotFoundException e1){
			e1.printStackTrace();
		}catch(IOException e1){
			e1.printStackTrace();
		}

		String[] todoStrings = new String[todo.size()];
		int count = 0;
		for(ToDoList t: todo)
		{
			todoStrings[count] = t.toString();
			count++;
		}
		setListAdapter(new ArrayAdapter<String>
			(this, android.R.layout.simple_list_item_1, todoStrings));
	}

	protected void onListItemClick(ListView l, View v, int position, long id)
	{
		super.onListItemClick(l, v, position, id);
		AlertDialog.Builder alert = new AlertDialog.Builder(DisplayTodo.this);
		alert.setTitle("Completed?");
		alert.setMessage("Have you finished this item?");
		
		final int pos = position;
		final View v2 = v;
		alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which){
				todo.remove(pos);
				writer = new ToDoWriter(v2.getContext());
				try{
					writer.writeTodo(todo);
				}catch (FileNotFoundException e){
					e.printStackTrace();
				}catch(IOException e){
					e.printStackTrace();
				}
				Intent myIntent = new Intent(v2.getContext(), DisplayTodo.class);
				startActivityForResult(myIntent,0);
			}
			});
		alert.setNegativeButton("No", new DialogInterface.OnClickListener(){
			public void onClick(DialogInterface dialog, int which){
			
			}
		});
		alert.show();
	}
	public void onBackPressed(){
		Intent myIntent = new Intent(Ctx, ToDoActivity.class);
		startActivityForResult(myIntent, 0);
	}
}

